import os
import logging
import requests
from pyfiglet import Figlet


def send_ding_ding(resource_name: str, status: str):
    """
    资源状态就绪信息推送至钉钉
    :param resource_name: 资源名称
    :param status: 资源状态
    :return 0: 推送失败
    """
    # 获取环境变量
    id = os.getenv('id')
    key = os.getenv('key')
    phones = os.getenv('phone')
    headers = {'Content-Type': 'application/json;charset=utf-8'}

    if not key or not id:
        logging.error("key or id is empty")
        return 0

    api = 'https://oapi.dingtalk.com/robot/send?access_token=' + key
    phone_at = ', '.join([f"@{num}" for num in phones.split(',')]) if phones else ""

    try:
        body = {
            "msgtype": "markdown",
            "markdown": {
                "title": f"资源更新状态 {resource_name}",
                "text": f"{resource_name}的状态为：{status} {phone_at.rstrip(',')}"
            },
            "at": {
                "atMobiles": [num.strip() for num in phones.split(',')] if phones else [],
                "isAtAll": False
            }
        }
    except Exception as e:
        logging.error(f"Failed to construct message body: {e}")
        return 0

    response = requests.post(api, json=body, headers=headers).json()

    if response.get('errmsg') == 'ok':
        logging.info("Message push successful")
        return 1
    else:
        logging.error(f"Message push failed: {response}")
        return 0


def generate_ascii_art(text, font="standard"):
    fig = Figlet(font=font)
    ascii_art = fig.renderText(text)
    print(ascii_art)
